import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:record/record.dart';
import 'dart:io';
import 'dart:async';
import '../constants/app_theme.dart';
import '../constants/app_constants.dart';
import '../providers/mood_provider.dart';
import '../models/mood_type.dart';
import '../models/mood_record.dart';
import '../models/media_attachment.dart';
import '../widgets/custom_app_bar.dart';
import '../widgets/mood_selector.dart';
import '../widgets/media_preview.dart';
import '../widgets/tag_input.dart';
import '../widgets/intensity_slider.dart';
import '../widgets/audio_recorder.dart';
import '../widgets/weather_selector.dart';
import 'package:record/record.dart' as record_package;

/// 记录页面
/// 用于创建和编辑情绪记录
class RecordScreen extends StatefulWidget {
  /// 要编辑的记录ID（可选）
  final String? recordId;
  
  /// 预设的情绪类型（可选）
  final MoodType? presetMood;

  const RecordScreen({
    super.key,
    this.recordId,
    this.presetMood,
  });

  @override
  State<RecordScreen> createState() => _RecordScreenState();
}

class _RecordScreenState extends State<RecordScreen>
    with TickerProviderStateMixin {
  // 表单控制器
  final _formKey = GlobalKey<FormState>();
  final _diaryController = TextEditingController();
  final _locationController = TextEditingController();
  final _scrollController = ScrollController();
  
  // 录音相关
  final _audioRecorder = record_package.AudioRecorder();
  Timer? _recordingTimer;
  
  // 状态变量
  MoodType? _selectedMood;
  int _intensity = 5;
  List<String> _tags = [];
  String _weather = '';
  List<MediaAttachment> _mediaAttachments = [];
  bool _isRecording = false;
  int _recordingDuration = 0;
  bool _isLoading = false;
  bool _hasUnsavedChanges = false;
  
  // 动画控制器
  late AnimationController _saveButtonController;
  late Animation<double> _saveButtonAnimation;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _initializeData();
    _setupTextListeners();
  }

  @override
  void dispose() {
    _diaryController.dispose();
    _locationController.dispose();
    _scrollController.dispose();
    _audioRecorder.dispose();
    _recordingTimer?.cancel();
    _saveButtonController.dispose();
    super.dispose();
  }

  /// 初始化动画
  void _initializeAnimations() {
    _saveButtonController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _saveButtonAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _saveButtonController,
      curve: Curves.easeInOut,
    ));
  }

  /// 初始化数据
  void _initializeData() {
    if (widget.presetMood != null) {
      _selectedMood = widget.presetMood;
    }
    
    if (widget.recordId != null) {
      _loadExistingRecord();
    }
  }

  /// 设置文本监听器
  void _setupTextListeners() {
    _diaryController.addListener(_onContentChanged);
    _locationController.addListener(_onContentChanged);
  }

  /// 内容变化处理
  void _onContentChanged() {
    if (!_hasUnsavedChanges) {
      setState(() {
        _hasUnsavedChanges = true;
      });
    }
  }

  /// 加载现有记录
  void _loadExistingRecord() async {
    try {
      final moodProvider = context.read<MoodProvider>();
      final record = await moodProvider.getRecordById(widget.recordId!);
      
      if (record != null && mounted) {
        setState(() {
          _selectedMood = record.moodType;
          _intensity = record.intensity;
          _tags = List.from(record.tags);
          _weather = record.weather ?? '';
          _mediaAttachments = List.from(record.mediaAttachments);
          _diaryController.text = record.diaryContent ?? '';
          _locationController.text = record.location ?? '';
        });
      }
    } catch (e) {
      _showErrorSnackBar('加载记录失败：$e');
    }
  }

  /// 保存记录
  void _saveRecord() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }
    
    if (_selectedMood == null) {
      _showErrorSnackBar('请选择心情');
      return;
    }
    
    setState(() {
      _isLoading = true;
    });
    
    _saveButtonController.forward();
    
    try {
      final moodProvider = context.read<MoodProvider>();
      
      if (widget.recordId != null) {
        // 更新现有记录
        final existingRecord = await moodProvider.getRecordById(widget.recordId!);
        if (existingRecord != null) {
          final updatedRecord = existingRecord.copyWith(
            moodType: _selectedMood!,
            diaryContent: _diaryController.text.trim(),
            intensity: _intensity,
            tags: _tags,
            weather: _weather,
            location: _locationController.text.trim(),
            mediaAttachments: _mediaAttachments,
            updatedAt: DateTime.now(),
          );
          await moodProvider.updateMoodRecord(updatedRecord);
        }
      } else {
        // 创建新记录
        final now = DateTime.now();
        final record = MoodRecord(
          moodType: _selectedMood!,
          diaryContent: _diaryController.text.trim(),
          intensity: _intensity,
          tags: _tags,
          weather: _weather,
          location: _locationController.text.trim(),
          mediaAttachments: _mediaAttachments,
          createdAt: now,
          updatedAt: now,
        );
        await moodProvider.addMoodRecord(record);
      }
      
      if (mounted) {
        _showSuccessSnackBar(
          widget.recordId != null ? '记录更新成功' : '记录保存成功',
        );
        
        // 延迟返回，让用户看到成功提示
        await Future.delayed(const Duration(milliseconds: 500));
        Navigator.pop(context, true);
      }
    } catch (e) {
      _showErrorSnackBar('保存失败：$e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        _saveButtonController.reverse();
      }
    }
  }

  /// 选择图片
  void _pickImage() async {
    try {
      final ImagePicker picker = ImagePicker();
      final List<XFile> images = await picker.pickMultiImage(
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 80,
      );
      
      for (final image in images) {
        final file = File(image.path);
        final fileSize = await file.length();
        
        if (fileSize > AppConstants.maxImageFileSize) {
          _showErrorSnackBar('图片大小不能超过${AppConstants.formatFileSize(AppConstants.maxImageFileSize)}');
          continue;
        }
        
        final attachment = MediaAttachment(
          moodRecordId: 0, // 临时值，保存时会更新
          type: MediaType.image,
          filePath: image.path,
          fileName: image.name,
          fileSize: fileSize,
          createdAt: DateTime.now(),
        );
        
        setState(() {
          _mediaAttachments.add(attachment);
          _hasUnsavedChanges = true;
        });
      }
    } catch (e) {
      _showErrorSnackBar('选择图片失败：$e');
    }
  }

  /// 拍照
  void _takePhoto() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 80,
      );
      
      if (image != null) {
        final file = File(image.path);
        final fileSize = await file.length();
        
        if (fileSize > AppConstants.maxImageFileSize) {
          _showErrorSnackBar('图片大小不能超过${AppConstants.formatFileSize(AppConstants.maxImageFileSize)}');
          return;
        }
        
        final attachment = MediaAttachment(
          moodRecordId: 0, // 临时值，保存时会更新
          type: MediaType.image,
          filePath: image.path,
          fileName: image.name,
          fileSize: fileSize,
          createdAt: DateTime.now(),
        );
        
        setState(() {
          _mediaAttachments.add(attachment);
          _hasUnsavedChanges = true;
        });
      }
    } catch (e) {
      _showErrorSnackBar('拍照失败：$e');
    }
  }

  /// 开始录音
  void _startRecording() async {
    try {
      // 检查权限
      final permission = await Permission.microphone.request();
      if (!permission.isGranted) {
        _showErrorSnackBar('需要麦克风权限才能录音');
        return;
      }
      
      // 开始录音
      final path = '${Directory.systemTemp.path}/audio_${DateTime.now().millisecondsSinceEpoch}.m4a';
      await _audioRecorder.start(
        const RecordConfig(
          encoder: AudioEncoder.aacLc,
          bitRate: 128000,
          sampleRate: 44100,
        ),
        path: path,
      );
      
      setState(() {
        _isRecording = true;
        _recordingDuration = 0;
      });
      
      // 开始计时
      _recordingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          _recordingDuration++;
        });
        
        // 最大录音时长限制
        if (_recordingDuration >= AppConstants.maxRecordingDuration) {
          _stopRecording();
        }
      });
    } catch (e) {
      _showErrorSnackBar('开始录音失败：$e');
    }
  }

  /// 停止录音
  void _stopRecording() async {
    try {
      final path = await _audioRecorder.stop();
      _recordingTimer?.cancel();
      
      setState(() {
        _isRecording = false;
      });
      
      if (path != null) {
        final file = File(path);
        final fileSize = await file.length();
        
        if (fileSize > AppConstants.maxAudioFileSize) {
          _showErrorSnackBar('录音文件过大');
          await file.delete();
          return;
        }
        
        final attachment = MediaAttachment(
          moodRecordId: 0, // 临时值，保存时会更新
          type: MediaType.audio,
          filePath: path,
          fileName: 'audio_${DateTime.now().millisecondsSinceEpoch}.m4a',
          fileSize: fileSize,
          duration: _recordingDuration,
          createdAt: DateTime.now(),
        );
        
        setState(() {
          _mediaAttachments.add(attachment);
          _hasUnsavedChanges = true;
        });
      }
    } catch (e) {
      _showErrorSnackBar('停止录音失败：$e');
    }
  }

  /// 删除媒体附件
  void _removeMediaAttachment(MediaAttachment attachment) {
    setState(() {
      _mediaAttachments.remove(attachment);
      _hasUnsavedChanges = true;
    });
    
    // 删除临时文件
    if (attachment.filePath.contains('temp')) {
      File(attachment.filePath).delete().catchError((_) => File(''));
    }
  }

  /// 显示媒体选择菜单
  void _showMediaPicker() {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: Icon(
                  Icons.photo_library,
                  color: AppTheme.primaryColor,
                ),
                title: const Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage();
                },
              ),
              ListTile(
                leading: Icon(
                  Icons.camera_alt,
                  color: AppTheme.primaryColor,
                ),
                title: const Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  _takePhoto();
                },
              ),
              ListTile(
                leading: Icon(
                  _isRecording ? Icons.stop : Icons.mic,
                  color: _isRecording ? AppTheme.errorColor : AppTheme.secondaryColor,
                ),
                title: Text(_isRecording ? '停止录音' : '录音'),
                onTap: () {
                  Navigator.pop(context);
                  if (_isRecording) {
                    _stopRecording();
                  } else {
                    _startRecording();
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.successColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }

  /// 处理返回按钮
  Future<bool> _onWillPop() async {
    if (!_hasUnsavedChanges) return true;
    
    final result = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('确认退出'),
          content: const Text('您有未保存的更改，确定要退出吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context, true),
              style: TextButton.styleFrom(
                foregroundColor: AppTheme.errorColor,
              ),
              child: const Text('退出'),
            ),
          ],
        );
      },
    );
    
    return result ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: AppTheme.backgroundColor,
        appBar: CustomAppBar(
          title: widget.recordId != null ? '编辑记录' : '记录心情',
          actions: [
            if (_hasUnsavedChanges)
              TextButton(
                onPressed: _isLoading ? null : _saveRecord,
                child: Text(
                  '保存',
                  style: TextStyle(
                    color: _isLoading ? Colors.white54 : Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
          ],
        ),
        body: Form(
          key: _formKey,
          child: SingleChildScrollView(
            controller: _scrollController,
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 情绪选择
                _buildMoodSection(),
                
                const SizedBox(height: 24),
                
                // 强度选择
                _buildIntensitySection(),
                
                const SizedBox(height: 24),
                
                // 日记内容
                _buildDiarySection(),
                
                const SizedBox(height: 24),
                
                // 标签
                _buildTagsSection(),
                
                const SizedBox(height: 24),
                
                // 天气和位置
                _buildContextSection(),
                
                const SizedBox(height: 24),
                
                // 媒体附件
                _buildMediaSection(),
                
                const SizedBox(height: 32),
                
                // 保存按钮
                _buildSaveButton(),
                
                const SizedBox(height: 24),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建情绪选择区域
  Widget _buildMoodSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '今天的心情如何？',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: 16),
          GridMoodSelector(
            selectedMood: _selectedMood,
            onMoodSelected: (mood) {
              setState(() {
                _selectedMood = mood;
                _hasUnsavedChanges = true;
              });
            },
            size: 56,
            crossAxisCount: 3,
          ),
        ],
      ),
    );
  }

  /// 构建强度选择区域
  Widget _buildIntensitySection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '情绪强度',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: 16),
          _buildIntensitySelector(),
        ],
      ),
    );
  }

  /// 构建强度选择器
  Widget _buildIntensitySelector() {
    return IntensitySlider(
      value: _intensity,
      onChanged: (value) {
        setState(() {
          _intensity = value;
        });
      },
      color: _selectedMood != null
          ? AppTheme.getMoodColor(_selectedMood!.name)
          : AppTheme.primaryColor,
    );
  }

  /// 构建日记区域
  Widget _buildDiarySection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '记录想法',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _diaryController,
            maxLines: 6,
            maxLength: AppConstants.maxDiaryLength,
            decoration: InputDecoration(
              hintText: '写下你的想法、感受或今天发生的事情...',
              hintStyle: TextStyle(
                color: AppTheme.textSecondaryColor,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: AppTheme.dividerColor,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: _selectedMood?.color ?? AppTheme.primaryColor,
                  width: 2,
                ),
              ),
              filled: true,
              fillColor: AppTheme.surfaceColor,
            ),
            style: TextStyle(
              color: AppTheme.textPrimaryColor,
              fontSize: 16,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标签区域
  Widget _buildTagsSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '添加标签',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: 16),
          TagInput(
            tags: _tags,
            onTagsChanged: (tags) {
              setState(() {
                _tags = tags;
                _hasUnsavedChanges = true;
              });
            },
            color: _selectedMood?.color ?? AppTheme.primaryColor,
          ),
        ],
      ),
    );
  }

  /// 构建上下文区域（天气和位置）
  Widget _buildContextSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '环境信息',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: 16),
          
          // 天气选择
          WeatherSelector(
            selectedWeather: _weather,
            onWeatherSelected: (weather) {
              setState(() {
                _weather = weather ?? '';
                _hasUnsavedChanges = true;
              });
            },
            layoutType: WeatherLayoutType.grid,
          ),
          
          const SizedBox(height: 16),
          
          // 位置输入
          Text(
            '位置',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          const SizedBox(height: 8),
          TextFormField(
            controller: _locationController,
            decoration: InputDecoration(
              hintText: '记录当前位置（可选）',
              hintStyle: TextStyle(
                color: AppTheme.textSecondaryColor,
              ),
              prefixIcon: Icon(
                Icons.location_on_outlined,
                color: AppTheme.textSecondaryColor,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: AppTheme.dividerColor,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: _selectedMood?.color ?? AppTheme.primaryColor,
                  width: 2,
                ),
              ),
              filled: true,
              fillColor: AppTheme.surfaceColor,
            ),
            style: TextStyle(
              color: AppTheme.textPrimaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建媒体区域
  Widget _buildMediaSection() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '添加媒体',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimaryColor,
                ),
              ),
              IconButton(
                onPressed: _showMediaPicker,
                icon: Icon(
                  Icons.add_circle_outline,
                  color: _selectedMood?.color ?? AppTheme.primaryColor,
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 音频录制器
          _buildAudioSection(),
          
          if (_mediaAttachments.isNotEmpty) ...[
            const SizedBox(height: 16),
            MediaPreview(
              attachments: _mediaAttachments,
              onRemove: _removeMediaAttachment,
            ),
          ] else ...[
            const SizedBox(height: 16),
            Center(
              child: Column(
                children: [
                  Icon(
                    Icons.add_photo_alternate_outlined,
                    size: 48,
                    color: AppTheme.textSecondaryColor.withOpacity(0.5),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '添加照片或录音',
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建音频录制区域
  Widget _buildAudioSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(
              Icons.mic,
              size: 20,
              color: AppTheme.textSecondaryColor,
            ),
            const SizedBox(width: 8),
            Text(
              '语音记录',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimaryColor,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        
        // 音频录制器
        CustomAudioRecorder(
          onRecordingComplete: (path) {
            final attachment = MediaAttachment(
              moodRecordId: 0, // 临时值，保存时会更新
              type: MediaType.audio,
              filePath: path,
              fileName: 'audio_${DateTime.now().millisecondsSinceEpoch}.m4a',
              fileSize: File(path).lengthSync(),
              createdAt: DateTime.now(),
            );
            
            setState(() {
              _mediaAttachments.add(attachment);
              _hasUnsavedChanges = true;
            });
          },
        ),
      ],
    );
  }

  /// 构建保存按钮
  Widget _buildSaveButton() {
    return AnimatedBuilder(
      animation: _saveButtonAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _saveButtonAnimation.value,
          child: SizedBox(
            width: double.infinity,
            height: 56,
            child: ElevatedButton(
              onPressed: _isLoading ? null : _saveRecord,
              style: ElevatedButton.styleFrom(
                backgroundColor: _selectedMood?.color ?? AppTheme.primaryColor,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                elevation: _isLoading ? 0 : 4,
                shadowColor: (_selectedMood?.color ?? AppTheme.primaryColor).withOpacity(0.3),
              ),
              child: _isLoading
                  ? const SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(
                      widget.recordId != null ? '更新记录' : '保存记录',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
            ),
          ),
        );
      },
    );
  }
}